import React, { useEffect, useState } from 'react';
import { getUserInfo } from '../../api/api';
import './Historical.css';
import { ArrowLeft } from '@react-vant/icons';
import { FixedSizeList as List } from 'react-window';

const Historical: React.FC<{ closeHistory: () => void, onHistoryClick: (historyData: { role: string; content: string }[], id: string) => void }> = ({ closeHistory, onHistoryClick }) => {
    const [data, setData] = useState<{ time: string; parsedContent: { role: string; content: string }[]; _id: string }[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        getUserInfo(localStorage.getItem('_id'))
            .then((res) => {
                const dates = res.data.dates;
                const parsedData = dates.map((item:any) => ({
                    ...item,
                    parsedContent: JSON.parse(item.content)
                }));
                setData(parsedData);
                console.log('data', parsedData);
                setLoading(false);
            })
            .catch((err) => {
                console.error('Error fetching data:', err);
                setError('Failed to load data');
                setLoading(false);
            });
    }, []);

    if (loading) return <div className="loading">Loading...</div>;
    if (error) return <div className="error">{error}</div>;

    const formatDate = (timestamp: string) => {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const Row = ({ index, style }: { index: number, style: React.CSSProperties }) => {
        const item = data[index];
        const userContent = item?.parsedContent?.find((dialogue: { role: string; content: string }) => dialogue.role === 'user')?.content;
        return (
            <>
            <div key={index} className="historical-item" style={style} onClick={() => onHistoryClick(item.parsedContent, item._id)}>
                <p className="time">{formatDate(item.time)}</p>
                <p className="content">
                    {userContent && userContent.length > 10 
                        ? userContent.substring(0, 10) + '...' 
                        : userContent}
                </p>
            </div>
            </>
        );
    };

    return (
        <div className='Historical'>
            <div>
                <h1><span onClick={closeHistory}><ArrowLeft fontSize={20} style={{position:'relative',top:'3px'}}/></span>历史记录</h1>
            </div>
            <List
                height={600}
                itemCount={data.length}
                itemSize={100}
                width={'100%'}
            >
                {Row}
            </List>
        </div>
    );
};

export default Historical;